#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：windows.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/21 上午8:58 
"""

from pathlib import Path


class WindowsPlatform:
	@staticmethod
	def create_lock(lock_path: Path):
		"""使用命名互斥体实现锁"""
		from win32event import CreateMutex
		from winerror import ERROR_ALREADY_EXISTS
		handle = CreateMutex(None, False, "Global\\FileMonitorMutex")
		if win32api.GetLastError() == ERROR_ALREADY_EXISTS:
			raise RuntimeError("Another instance is already running")
		return handle

	@staticmethod
	def get_system_paths():
		"""获取Windows系统路径"""
		from win32com.shell import shellcon, shell
		docs = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
		return {
			"config": Path(docs) / "FileMonitor",
			"logs": Path(docs) / "Logs",
			"runtime": Path("C:/ProgramData/FileMonitor")
		}

	@staticmethod
	def create_watcher(callback):
		"""使用ReadDirectoryChangesW实现实时监控"""
		import win32file
		import win32con

		def watch_loop(path):
			hDir = win32file.CreateFile(
				path,
				win32con.GENERIC_READ,
				win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
				None,
				win32con.OPEN_EXISTING,
				win32con.FILE_FLAG_BACKUP_SEMANTICS,
				None
			)
			while True:
				results = win32file.ReadDirectoryChangesW(
					hDir,
					1024,
					True,
					win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
					win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
					win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
					win32con.FILE_NOTIFY_CHANGE_SIZE |
					win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
					None
				)
				callback(results)

		return watch_loop
